/** 
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.merchant.service.impl;

import cn.horesman.service.HoresmanService;
import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.util.CommonUtil;
import cn.itcast.util.CookieUtil;
import cn.itcast.util.DoubleUtils;
import cn.itcast.util.RedisUtil;
import cn.merchant.service.merchantService;
import cn.web.web_module.entity.WithdrawRechargeInfo;
import cn.web.web_module.mapper.WithdrawRechargeInfoMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.itcast.util.Date.getTimesevening;
import static cn.itcast.util.Date.getTimesmorning;
import static cn.itcast.util.OrderNumber.getOrderIdByTime;

/**   
 * @title: userServiceImpl.java 
 * @package com.job.service.lmpl 
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2019年1月25日 下午3:21:04 
 * @version: V1.0   
*/
@Slf4j
@Service
public class merchantServiceImpl implements merchantService {

	@Resource
	cn.itcast.mapper.packageOrderMapper packageOrderMapper;
	@Resource
	cn.itcast.mapper.packageOrderItemMapper packageOrderItemMapper;
	@Resource
	merchantMapper merchantMapper;

    @Resource
	classsifyMapper classsifyMapper;

    @Resource
	accountMapper accountMapper;

    @Resource
	earningsMapper earningsMapper;

    @Resource
	horsemanMapper horsemanMapper;

    @Resource
	rechargeMapper rechargeMapper;

    @Resource
	withdrawMapper withdrawMapper;

	@Resource
	orderMapper orderMapper;

	@Resource
	orderItemMapper orderItemMapper;

	@Autowired
	RedisUtil redisTemplate;


	@Resource
	private StringRedisTemplate stringRedisTemplate;

	@Resource
	private WithdrawRechargeInfoMapper withdrawRechargeInfoMapper;

	@Override
	public Map<String,Object> login(String username, String password) {
		//返回Map
		Map<String,Object> map = new HashMap<String, Object>();
		boolean islogin=true;
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria = hEx.createCriteria();
		criteria.andMerchantNumberEqualTo(username);
		List<merchant> merchants = merchantMapper.selectByExample(hEx);
		if(!merchants.isEmpty()) {
			String pwd = merchants.get(0).getMerchantPassword();
			if(password.equals(pwd)) {
				//管理员数据返回前台
				map.put("horsemen",merchants.get(0));
				map.put("islogin", islogin);
				//System.out.println(template.opsForValue().get(token));
				log.debug(merchants.get(0).getMerchantNumber());
			}else {
				islogin = false;
				map.put("horsemen","");
				map.put("islogin", islogin);
				log.debug("密码错误");
			}
		}else {
			islogin = false;
			map.put("horsemen","");
			map.put("islogin", islogin);
			log.debug("用户不存在");
		}
		return map;
	}
	/**
	 *
	 * @Description:
	 * 获取用户各状态订单
	 * @auther: 欧阳辉
	 * @date: 11:36 2020/3/17
	 * @param: [orderStatus, openId]
	 * @return: java.util.List<cn.itcast.pojo.order>
	 *
	 */
	@Override
	public List<packageOrder> findMerchantOrder(String orderStatus, String openId) {
		log.debug(orderStatus+"openId"+openId);

		//查找父账户
        merchantExample mEx = new merchantExample();
        merchantExample.Criteria criteria = mEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        merchant merchant = merchantMapper.selectByExample(mEx).get(0);

        packageOrderExample oEx = new packageOrderExample();
        packageOrderExample.Criteria criteriaPack = oEx.createCriteria();

        if(merchant.getMerchantFid()==0){
            criteriaPack.andRecycleNumberEqualTo(merchant.getMerchantNumber());
        }else {
            criteriaPack.andRecycleNumberEqualTo( merchantMapper.selectByPrimaryKey(merchant.getMerchantFid()).getMerchantNumber());
        }


//      criteriaPack.andStatusEqualTo(orderStatus);
//		List<packageOrder> packageOrders = packageOrderMapper.selectByExample(oEx);

		List<packageOrder> packageOrders =packageOrderMapper.selectMerchantFiftyData(orderStatus,merchant.getMerchantNumber());
		for (int i = 0 ; i <packageOrders.size() ;i++){
			packageOrderItemExample oIEx = new packageOrderItemExample();
			packageOrderItemExample.Criteria criteria1 = oIEx.createCriteria();
			criteria1.andOrderIdEqualTo(packageOrders.get(i).getId());
			List<packageOrderItem> packageOrderItems = packageOrderItemMapper.selectByExample(oIEx);
			packageOrders.get(i).setPackageOrderItems(packageOrderItems);
		}
		return packageOrders;
	}


	/**
	 *
	 * @Description:
	 * 获取用户各状态订单
	 * @auther: 欧阳辉
	 * @date: 11:36 2020/3/17
	 * @param: [orderStatus, openId]
	 * @return: java.util.List<cn.itcast.pojo.order>
	 *
	 */
	@Override
	public List<List<order>> findHoresmanOverOrder(String openId) {
		log.debug("openId"+openId);

		//查找父账户
		merchantExample mEx = new merchantExample();
		merchantExample.Criteria criteria = mEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		merchant merchant = merchantMapper.selectByExample(mEx).get(0);

		horsemanExample hEx = new horsemanExample();
			horsemanExample.Criteria criteriahor = hEx.createCriteria();

			if(merchant.getMerchantFid()==0){
			criteriahor.andHorsemanReferrerEqualTo(merchant.getMerchantNumber());
		}else {
			System.err.println("难道来到这里："+merchantMapper.selectByPrimaryKey(merchant.getMerchantFid()).getMerchantNumber());
			criteriahor.andHorsemanReferrerEqualTo( merchantMapper.selectByPrimaryKey(merchant.getMerchantFid()).getMerchantNumber());
		}
		List<horseman> horsemen = horsemanMapper.selectByExample(hEx);
		if(horsemen.isEmpty()){
			return null;
		}else {
			List<List<order>> orders = new ArrayList<>();
			for (horseman horseman : horsemen) {
				orderExample oEx = new orderExample();
				orderExample.Criteria criteriaPack = oEx.createCriteria();
				criteriaPack.andOrderStateEqualTo("已完成");
				criteriaPack.andHorsemanAccountEqualTo(horseman.getOpenId());
				List<order> order = orderMapper.selectByExample(oEx);
				for (int i = 0 ; i <order.size() ;i++){
					orderItemExample oIEx = new orderItemExample();
					orderItemExample.Criteria criteria1 = oIEx.createCriteria();
					criteria1.andOrderIdEqualTo(order.get(i).getId());
					List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
					order.get(i).setOrderItems(orderItems);

				}
				orders.add(order);
			}
			return orders;
		}


	}

	@Override
	public boolean acceptOrder(Integer orderId) {
		packageOrder packageOrder = new packageOrder();
		packageOrder.setId(orderId);
		packageOrder.setStatus("进行中");
		int i = packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
		packageOrder dataOrder = packageOrderMapper.selectByPrimaryKey(orderId);
		if(i==1){

			return true;
		}else {
			return false;
		}
	}

	@Override
	public packageOrder findOneOrder(String orderId) {
		packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(Integer.parseInt(orderId));

		packageOrderItemExample oIEx = new packageOrderItemExample();
		packageOrderItemExample.Criteria criteria1 = oIEx.createCriteria();
		criteria1.andOrderIdEqualTo(Integer.parseInt(orderId));
		List<packageOrderItem> packageOrderItems = packageOrderItemMapper.selectByExample(oIEx);
		packageOrder.setPackageOrderItems(packageOrderItems);
		return packageOrder;
	}

    @Override
    public boolean abnormalOrder(Integer orderId, String explain) {
        //返回是否修改成功
        boolean isdelect = true;
        if(StringUtils.isNotBlank(ObjectUtils.toString(orderId))){
			packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(orderId);
            if(StringUtils.isNotBlank(ObjectUtils.toString(packageOrder.getId()))){
				packageOrder.setStatus("异常订单");
				packageOrder.setOrderExplain(explain);
				packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
            }else {
                isdelect = false;
                log.debug("该订单不存在");
            }
        }else {
            isdelect = false;
            log.debug("传入订单Id为空");
        }
        return isdelect;
    }

    @Override
    public boolean updateUserInfo(merchant merchant) {
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria= hEx.createCriteria();
		criteria.andOpenIdEqualTo(merchant.getOpenId());
		List<cn.itcast.pojo.merchant> merchants = merchantMapper.selectByExample(hEx);
		merchant.setMerchantId(merchants.get(0).getMerchantId());
		int i = merchantMapper.updateByPrimaryKeySelective(merchant);
        if(i==1){
            return true;
        }else{
            return false;
        }
    }

	@Override
	public boolean updateOrder(packageOrder packageOrder) {
		int i = packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
		if(i==1){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean updateOrderItem(packageOrderItem packageOrderItem,Integer orderId) {
		packageOrder packageOrder = new packageOrder();
		packageOrder.setStatus("待支付");
		packageOrder.setId(orderId);
		packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
		int i = packageOrderItemMapper.updateByPrimaryKeySelective(packageOrderItem);
		if(i==1){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean addOrderItem(Integer orderId,Integer classifyId) {

		classsify classsify = classsifyMapper.selectByPrimaryKey(classifyId);
		//查询是否存在
		packageOrderItemExample oEx = new packageOrderItemExample();
		packageOrderItemExample.Criteria criteria = oEx.createCriteria();
		 criteria.andOrderIdEqualTo(orderId);
		List<packageOrderItem> packageOrderItems = packageOrderItemMapper.selectByExample(oEx);
		for(int i=0;i<packageOrderItems.size();i++){
			if(classsify.getName().equals(packageOrderItems.get(i).getProductType())){
				return false;
			}

		}
		packageOrderItem packageOrderItem = new packageOrderItem();
		packageOrderItem.setProductType(classsify.getName());
		packageOrderItem.setOrderId(orderId);
		int i = packageOrderItemMapper.insertSelective(packageOrderItem);
		if(i==1){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public boolean delectOrderItem(Integer orderId) {
		int i = packageOrderItemMapper.deleteByPrimaryKey(orderId);
		if(i==1){
			return true;
		}else{
			return false;
		}

	}

	@Override
	public boolean createAccount(account account) {
		accountExample aEx = new accountExample();
		accountExample.Criteria criteria = aEx.createCriteria();
		criteria.andOpenIdEqualTo(account.getOpenId());
		List<cn.itcast.pojo.account> accounts = accountMapper.selectByExample(aEx);
		if(accounts.isEmpty()){
			int i = accountMapper.insertSelective(account);
			if(i==1){
				return true;
			}else{
				return false;
			}
		}else {
			return false;
		}

	}

	@Override
	@Transactional
	public boolean toPayByOrder(Integer orderId, String openId) {
	    try {
            if (!ifSendPay(openId, orderId)) {
                return false;
            }
            if (!ifPackageOrderState(orderId)) {
                return false;
            }
            merchantExample hEx = new merchantExample();
            merchantExample.Criteria criteria = hEx.createCriteria();
            criteria.andOpenIdEqualTo(openId);
            List<merchant> merchants = merchantMapper.selectByExample(hEx);
            if (merchants.isEmpty()) {
                return false;
            } else {
                if (merchants.get(0).getMerchantFid() != 0) {
                    openId = merchantMapper.selectByPrimaryKey(merchants.get(0).getMerchantFid()).getOpenId();
                }
            }
            accountExample aEx = new accountExample();
            accountExample.Criteria acccriteria = aEx.createCriteria();
            acccriteria.andOpenIdEqualTo(openId);
            acccriteria.andAccountTypeidEqualTo(3);
            List<account> accounts = accountMapper.selectByExample(aEx);
            if (accounts.isEmpty()) {
                return false;
            } else {
                //查询订单金额
                packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(orderId);
                if (new BigDecimal(accounts.get(0).getAccountMoneyBalance()).compareTo(new BigDecimal(packageOrder.getOrderSumRecycle())) == -1) {
                    return false;
                } else {
                    //获取用户账户
                    accountExample userEx = new accountExample();
                    accountExample.Criteria userCriteria = userEx.createCriteria();
                    userCriteria.andOpenIdEqualTo(packageOrder.getOpenId());
                    userCriteria.andAccountTypeidEqualTo(1);
                    List<account> userAccounts = accountMapper.selectByExample(userEx);

					//修改骑手账户余额
					Double add = DoubleUtils.add(userAccounts.get(0).getAccountMoneyBalance(), packageOrder.getOrderSumRecycle());
					userAccounts.get(0).setAccountMoneyBalance(add);
                    userAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(userAccounts.get(0).getAccountMoneyRental(), packageOrder.getOrderSumRecycle()));
                    userAccounts.get(0).setAccountEarningsConsume(DoubleUtils.add(userAccounts.get(0).getAccountEarningsConsume(), packageOrder.getOrderSumRecycle()));
					//修改商家账户余额
                    log.debug("账户余额:" + accounts.get(0).getAccountMoneyBalance());
                    log.debug("订单金额:" + packageOrder.getOrderSumRecycle());
                    accounts.get(0).setAccountMoneyBalance(DoubleUtils.sub(accounts.get(0).getAccountMoneyBalance(), packageOrder.getOrderSumRecycle()));
                    log.debug("支付后账户余额:" + accounts.get(0).getAccountMoneyBalance());

                    int i = accountMapper.updateByPrimaryKeySelective(accounts.get(0));
                    if (i == 1) {
                        int j = accountMapper.updateByPrimaryKeySelective(userAccounts.get(0));

                        //添加收益记录
                        earnings earnings = new earnings();
                        earnings.setAccountId(userAccounts.get(0).getAccountId());
                        earnings.setName(userAccounts.get(0).getAccountName());
                        earnings.setPhone(userAccounts.get(0).getAccountPhone());
                        earnings.setOpenid(userAccounts.get(0).getOpenId());
                        earnings.setSource("回收资金");
                        earnings.setNumber(getOrderIdByTime());
                        earnings.setNum(packageOrder.getOrderSumRecycle());
                        earnings.setState("已到账");
                        earnings.setEarningsExplain("回收站收货，换取佣金");
                        //骑手交货后的总额
                        earnings.setCountnum(add);

                        //生成收益记录
                        int i1 = earningsMapper.insertSelective(earnings);
                        if (i1 == 1) {
                            log.debug("生成收益记录成功");
                        } else {
                            log.debug("生成收益记录失败");
                        }


                        //更新订单
                        packageOrder.setStatus("已完成");
                        packageOrder.setPayTime(new Date());
                        packageOrder.setRecycleChildrenNumber(merchants.get(0).getMerchantNumber());
                        packageOrderMapper.updateByPrimaryKeySelective(packageOrder);


                        //添加骑手出货记录
                        List<order> orders = orderMapper.selectHorsemanStocksOrder(packageOrder.getOpenId());
                        WithdrawRechargeInfo withdrawRechargeInfo = new WithdrawRechargeInfo();
                        withdrawRechargeInfo.setOrderId(orders.get(0).getId());
                        withdrawRechargeInfo.setPackageOrderId(packageOrder.getId());
                        withdrawRechargeInfo.setPackageOrderMoney(packageOrder.getOrderSumRecycle().longValue());
                        withdrawRechargeInfo.setHorsemanName(packageOrder.getHorsemanName());
                        withdrawRechargeInfo.setHorsemanAccount(packageOrder.getOpenId());
                        int i2 = withdrawRechargeInfoMapper.insertSelective(withdrawRechargeInfo);
                        System.out.println(i2);

                        return true;
                    } else {
                        log.debug("账户金额修改失败");
                        return false;
                    }
                }
            }
        }finally {
	        if (!stringRedisTemplate.opsForValue().get(openId + ":" + orderId).isEmpty()){
                stringRedisTemplate.delete(openId + ":" + orderId);
            }
        }
	}

	private boolean ifPackageOrderState(Integer orderId) {
		packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(orderId);
		if (packageOrder.getStatus().equals("已完成")){
			return false;
		}
		return true;
	}

	private boolean ifSendPay(String openId, Integer orderId) {
		Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent(openId + ":" + orderId, orderId + "");
		return ifAbsent;
	}

	@Override
    public boolean finishOrder(Integer orderId, String openId) {
        merchantExample hEx = new merchantExample();
        merchantExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<merchant> merchants = merchantMapper.selectByExample(hEx);
        if(merchants.isEmpty()){
            return false;
        }else {
            packageOrder packageOrder = new packageOrder();
            packageOrder.setStatus("已完成");
            packageOrder.setPayTime(new Date());
            packageOrder.setId(orderId);
            packageOrder.setRecycleChildrenNumber(merchants.get(0).getMerchantNumber());
            int i = packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
            return i==1;
        }
    }

	@Override
	public Map<String, List<Map<String, String>>> findChildrenMerchant(String openId) {
		Map<String,List<Map<String,String>>> result = new HashMap<>();
		List<Map<String,String>> merchantList = new ArrayList<>();
		Map<String,String> merchantMap = new HashMap<>();
		merchantExample mEx = new merchantExample();
		merchantExample.Criteria criteria = mEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		String number = merchantMapper.selectByExample(mEx).get(0).getMerchantNumber();
		merchantExample cmEx = new merchantExample();
		merchantExample.Criteria ccriteria = cmEx.createCriteria();
		ccriteria.andMerchantNumberEqualTo(number);
		List<merchant> merchants = merchantMapper.selectByExample(cmEx);
		for (merchant merchant : merchants) {
			packageOrderExample poEx = new packageOrderExample();
			packageOrderExample.Criteria poCriteria = poEx.createCriteria();
			poCriteria.andPayTimeBetween(getTimesmorning(),getTimesevening());
		}
		return null;
	}

	@Override
	public boolean registMerchant(String phone, String password, String name, int code,String receivingtype,String merchantLat,String merchantLon) {
		if(!StringUtils.isNotBlank(ObjectUtils.toString(redisTemplate.get(phone+"code")))){
			return false;
		}
		int codeRedis = (int) redisTemplate.get(phone+"code");
		log.debug(String.valueOf(codeRedis));
		log.debug(String.valueOf(code));

		if(code==codeRedis){
			merchant merchant = new merchant();
			merchant.setMerchantName(name);
			merchant.setMerchantPhone(phone);
			merchant.setMerchantNumber(phone);
			merchant.setMerchantPassword(password);
			merchant.setReceivingtype(receivingtype);
			merchant.setMerchantLat(merchantLat);
			merchant.setMerchantLon(merchantLon);
			merchant.setMerchantFid(0);
			merchant.setMerchantIsopen("0");
			int i = merchantMapper.insertSelective(merchant);
			return i==1;
		}
		return false;
	}

	@Override
	public boolean updatePassword(String password, String passwordOld,String openId) {
		merchantExample mEx = new merchantExample();
		merchantExample.Criteria criteria = mEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		List<merchant> merchants = merchantMapper.selectByExample(mEx);
		if(passwordOld.equals(merchants.get(0).getMerchantPassword())){
			merchants.get(0).setMerchantPassword(password);
			int i = merchantMapper.updateByPrimaryKeySelective(merchants.get(0));
			return i==1;
		}else {
			return false;
		}
	}

	@Override
	public List<merchant> selectLatLon() {
		List<merchant>list=merchantMapper.selectLatLon();
		return list;
	}

	@Override
	public boolean updatachantmessage(merchant merchant) {
		return merchantMapper.updatechantmessagemapp(merchant);
	}

	@Override
	public merchant selectidmerchant(String opnid) {
		return merchantMapper.selectidmerchantmapp(opnid);
	}

	@Override
	public List<order> merchantlist(String merchantopenid) {
		return orderMapper.merchantmapp(merchantopenid);
	}

	@Override
	public int updatemerchanttype(String ordernumber, String payproducttype) {
		return orderMapper.updatemerchanttypemapp(ordernumber,payproducttype);
	}

	@Override
	public order merchantpayuser(Integer id) {
		return orderMapper.selectByPrimaryKey(id);
	}

	@Override
	public account accountmoney(String openid) {
		return accountMapper.selectByAccountOpenid(openid);
	}

	@Override
	public int accountupdatemoney(account account) {
		return accountMapper.updateaccountmoney(account);
	}

	@Override
	public int orderupdate(order order) {
		return orderMapper.orderupdate(order);
	}

	@Override
	public int addaccount(account account) {
		return accountMapper.insert(account);
	}

	@Override
	public int addearnings(earnings earnings) {
		return earningsMapper.insert(earnings);
	}

	@Override
	public merchant selectopenidmerchat(String openid) {
		return null;
	}

	@Override
	public boolean cancelmerchaent(String orderid) {
		return orderMapper.cancelmerchaentmapp(orderid);
	}

	/**
	 *
	 * @Description:
	 * 随机生成订单号
	 * @auther: 欧阳辉
	 * @date: 8:23 2020/3/17
	 * @param: []
	 * @return: java.lang.String
	 *
	 */
	public String getOrderIdByTime() {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String newDate=sdf.format(new Date());
		String result="";
		Random random=new Random();
		for(int i=0;i<3;i++){
			result+=random.nextInt(10);
		}
		return newDate+result;
	}


	@Override
	public merchant findUserInfo(String openId) {
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria = hEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		List<merchant> merchant = merchantMapper.selectByExample(hEx);
		if(merchant.isEmpty()){
			return null;
		}else {
			return merchant.get(0);
		}

	}

	@Override
	public boolean toLatAndLon(String lat, String lon,String openId) {
		merchant merchant = new merchant();
		merchant.setMerchantLat(lat);
		merchant.setMerchantLon(lon);
		merchant.setOpenId(openId);
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria = hEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		int i = merchantMapper.updateByExampleSelective(merchant, hEx);
		if(i==1){
			return true;
		}else {
			return false;
		}
	}


	@Override
	public boolean addImgPath(String path,Integer id) {
		packageOrderItem packageOrderItem = packageOrderItemMapper.selectByPrimaryKey(id);
		packageOrderItem.setImage(packageOrderItem.getImage()+','+path);
		int i = packageOrderItemMapper.updateByPrimaryKeySelective(packageOrderItem);
		if(i==1){
			return true;
		}else {
			return false;
		}
	}


	@Override
	public merchant findHoresmanArea(String openId) {
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria = hEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		List<merchant> merchants = merchantMapper.selectByExample(hEx);
		if(merchants.isEmpty()){
			return null;
		}else {
			return merchants.get(0);
		}

	}

	@Override
	public boolean cancelOrder(Integer orderId) {
		packageOrder packageOrder = new packageOrder();
		packageOrder.setId(orderId);
		packageOrder.setStatus("待派单");
		int i = packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
		packageOrder dataOrder = packageOrderMapper.selectByPrimaryKey(packageOrder.getId());
		if(i==1){
			return true;
		}else {
			return false;
		}

	}


	@Override
	public List<account> findMerchantAccount(String openId) {
        merchantExample hEx = new merchantExample();
        merchantExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<merchant> merchants = merchantMapper.selectByExample(hEx);
        if(merchants.isEmpty()){
            return null;
        }else {
            if(merchants.get(0).getMerchantFid()!=0){
                openId = merchantMapper.selectByPrimaryKey(merchants.get(0).getMerchantFid()).getOpenId();
            }
        }
		accountExample aEx = new accountExample();
		accountExample.Criteria acccriteria = aEx.createCriteria();
        acccriteria.andOpenIdEqualTo(openId);
        acccriteria.andAccountTypeidEqualTo(3);
		List<account> accounts = accountMapper.selectByExample(aEx);
		return accounts;
	}

	@Override
	public List<recharge> findrechargeRecord(String openId) {
        merchantExample hEx = new merchantExample();
        merchantExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<merchant> merchants = merchantMapper.selectByExample(hEx);
        if(merchants.isEmpty()){
            return null;
        }else {
            if(merchants.get(0).getMerchantFid()!=0){
                openId = merchantMapper.selectByPrimaryKey(merchants.get(0).getMerchantFid()).getOpenId();
            }
        }
		rechargeExample rechargeExample = new rechargeExample();
		rechargeExample.Criteria recriteria = rechargeExample.createCriteria();
		recriteria.andOpenIdEqualTo(openId);
		return rechargeMapper.selectByExample(rechargeExample);
	}

	@Override
	public List<withdraw> findWithdrawRecord(String openId) {
        merchantExample hEx = new merchantExample();
        merchantExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<merchant> merchants = merchantMapper.selectByExample(hEx);
        if(merchants.isEmpty()){
            return null;
        }else {
            if(merchants.get(0).getMerchantFid()!=0){
                openId = merchantMapper.selectByPrimaryKey(merchants.get(0).getMerchantFid()).getOpenId();
            }
        }
		withdrawExample wEx = new withdrawExample();
		wEx.setOrderByClause("apply_time DESC");
		withdrawExample.Criteria wicriteria = wEx.createCriteria();
		wicriteria.andOpenIdEqualTo(openId);
		return withdrawMapper.selectByExample(wEx);
	}


    @Override
    public boolean addRecharge(recharge recharge) {
        int i = rechargeMapper.insertSelective(recharge);
        if(i==1){
            return true;
        }else {
            return false;
        }
    }


    @Override
    public boolean updateRecharge(recharge recharge) {
        //获取记录信息
        rechargeExample rEx = new rechargeExample();
        rechargeExample.Criteria criteria = rEx.createCriteria();
        criteria.andRechargeNumberEqualTo(recharge.getRechargeNumber());
        List<cn.itcast.pojo.recharge> recharges = rechargeMapper.selectByExample(rEx);
        if(recharges.isEmpty()){
            return false;
        }else {
            //修改记录状态
            recharge recharge1 = recharges.get(0);
            recharge1.setBillState(recharge.getBillState());
            recharge1.setPayState(recharge.getPayState());
            int i = rechargeMapper.updateByPrimaryKeySelective(recharge1);
            if(i==1){
                //修改账户金额
                accountExample aEx = new accountExample();
                accountExample.Criteria criteria1 = aEx.createCriteria();
                criteria1.andOpenIdEqualTo(recharge1.getOpenId());
                criteria1.andAccountTypeidEqualTo(3);
                List<account> accounts = accountMapper.selectByExample(aEx);
                if(accounts.isEmpty()){
                    return false;
                }else {
                    account account = accounts.get(0);
                    account.setAccountMoneyBalance(account.getAccountMoneyBalance()+recharge1.getRechargeSum());
                    account.setAccountMoneyRental(account.getAccountMoneyRental()+recharge1.getRechargeSum());
                    accountMapper.updateByPrimaryKeySelective(account);
                    //创建收益记录
                    earnings earnings = new earnings();
                    earnings.setAccountId(account.getAccountId());
                    earnings.setName(account.getAccountName());
                    earnings.setPhone(account.getAccountPhone());
                    earnings.setOpenid(account.getOpenId());
                    earnings.setSource("微信充值");
                    earnings.setNumber(getOrderIdByTime());
                    earnings.setNum(recharge1.getRechargeSum());
                    earnings.setState("已到账");
                    earnings.setEarningsExplain("微信充值");
                    int i1 = earningsMapper.insertSelective(earnings);
                    if(i1 == 1){
                        log.debug("收益记录成功");
                    }else {

                        log.debug("收益记录失败");
                    }
                    return true;
                }
            }else {
                return false;
            }
        }

    }


	@Override
	public List<horseman> findHoresman(String openId) {
		merchantExample hEx = new merchantExample();
		merchantExample.Criteria criteria = hEx.createCriteria();
		criteria.andOpenIdEqualTo(openId);
		List<merchant> merchants = merchantMapper.selectByExample(hEx);
		String number = "";
		if(merchants.isEmpty()){
			return null;
		}else {
			if(merchants.get(0).getMerchantFid()!=0){
				number = merchantMapper.selectByPrimaryKey(merchants.get(0).getMerchantFid()).getMerchantNumber();
			}else {
				number = merchants.get(0).getMerchantNumber();
			}
		}
		horsemanExample aEx = new horsemanExample();
		horsemanExample.Criteria acccriteria = aEx.createCriteria();
		acccriteria.andHorsemanReferrerEqualTo(number);
		List<horseman> horsemen = horsemanMapper.selectByExample(aEx);
		return horsemen;
	}





}
